from flask import Blueprint,request,jsonify
import json
from db import db


bp_shop  = Blueprint('kaoshi',__name__)


#分类
@bp_shop.route('/add/',methods=['POST',"GET"])
def add():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(request.data)
        else:
            data = request.form
            
        name = data['name']
        
        sql = "insert into type1 values(%d,'%s')" %(0,name)
        db.insert(sql)
        print(name)
        
        return 'ok'
    elif request.method == 'GET':
        sql = "select * from type1"
        res = db.get_all(sql)
        return jsonify({"code":200,'list':res})

#商品
@bp_shop.route('/shopadd/',methods=['GET','POST','DELETE'])
def shopadd():
    if request.method =='POST':
        data = request.data
        if data:
            data = json.loads(request.data)
        else:
            data = request.form
        sql = "insert into shop1 values(%d,'%s',%d)"%(0,data['name'],int(data['cid']))
        db.insert(sql)
        
        return jsonify({"code":200})
    elif request.method =='GET':
        uid = int(request.args.get('uid'))
        print(uid)
        if uid ==0:
            sql = "select * from shop1 order by id desc"
            res = db.get_all(sql)
            return jsonify({"code":200,'list':res})
        else:
            sql = "select * from shop1 where cid=%d order by id desc"%uid
            res = db.get_all(sql)
            return jsonify({"code":200,'list':res})
    else:
        id = request.args.get('id')
        print(id,type(id))
        sql = "delete from shop1 where id=%d"%(int(id))
        db.delete(sql)
        return jsonify({"code":200})
    
@bp_shop.route('/deleteall/',methods=['DELETE'])
def deleteall():
    if request.method == 'DELETE':
        id =request.args.get('id')
        ids = id.split(',')
        print(ids)

        for i in ids:
            sql = "delete from shop1 where id in(%d)"% int(i)
            db.delete(sql)
        return jsonify({"code":200})
        
    
    
    
    
    
    
    
    